﻿using System;
using System.Net;
using SportInfoService.Helpers;
using System.Text;
using System.Collections.Generic;
using MatchResults.Model;
using System.Linq;
using MatchResults.ViewModel;

namespace MatchResults.Helpers
{
    public class ServiceHelper
    {
        static string MatchResultUrl = "http://www.iddaa.com.tr/XML/FinishedMatches/index.htm?thd={0}&foraccess=KSsec654";
        static string MatchProgramsUrl = "http://www.iddaa.com.tr/XML/IDDAAMACPROGRAMI/index.htm?iddaadrawid={0}&foraccess=KSsec654";
        static string LiveMatchResultUrl = "http://www.iddaa.com.tr/XML/SkorYayin/index.htm?foraccess=KSsec654";

        //public event EventHandler OnCompleteGetResult;

        public void GetMessages(Action<IEnumerable<MatchResultViewModel>> callback, string daysBefor)
        {

            string matchResultUrl = string.Format(MatchResultUrl, daysBefor);
            WebClient wc = GetWebClient();
            wc.DownloadStringCompleted += (s, e) =>
                callback(e.Error == null ? ParseData(e.Result) : Enumerable.Empty<MatchResultViewModel>());

            wc.DownloadStringAsync(new Uri(matchResultUrl));


        }

        private IEnumerable<MatchResultViewModel> ParseData(string result)
        {
            result = result.Substring(result.IndexOf("<League"));
            result = result.Substring(0, result.IndexOf("<!--"));
            League league = XMLHelper.Deserialize<League>(result, Encoding.UTF8);

            //return league.Match.Select(new MatchResultModel {  });
            List<MatchResultViewModel> data = new List<MatchResultViewModel>();
           
            for (int i = 0; i < league.Match.Count; i++)
            {
                data.Add(new MatchResultViewModel
                {
                    Flag = string.Format("/MatchResults;component/images/flags/{0}.png", league.Match[i].countryid)
                    ,
                    Lig = league.Match[i].lig
                    ,
                    Takimlar = league.Match[i].takimlar
                    ,
                    Saat = league.Match[i].saatmac
                    ,
                    Iy = league.Scores[i].scorehalfhome + "-" + league.Scores[i].scorehalfaway
                    ,
                    Ms = league.Scores[i].scorecurrenthome + "-" + league.Scores[i].scorecurrentaway
                });
            }
            return data;
        }

        /// <summary>
        /// Method to get match result
        /// </summary>
        /// <param name="daysBefor">param to shows how many days befor</param>
        /// <returns></returns>
        public void GetMatchResult(string daysBefor)
        {
            string matchResultUrl = string.Format(MatchResultUrl, daysBefor);
            WebClient wc = GetWebClient();
            wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(GetMatchResultCompleted);
            wc.DownloadStringAsync(new Uri(matchResultUrl));
        }

        void GetMatchResultCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            string result = e.Result;
            result = result.Substring(result.IndexOf("<League"));
            result = result.Substring(0, result.IndexOf("<!--"));
            League league = XMLHelper.Deserialize<League>(result, Encoding.UTF8);

            //App.MatchResultList.Clear();
            //for (int i = 0; i < league.Match.Count; i++)
            //{
            //    App.MatchResultList.Add(new MatchResultModel
            //     {
            //         Flag = string.Format("/MatchResults;component/images/flags/{0}.png", league.Match[i].countryid)
            //         ,
            //         Lig = league.Match[i].lig
            //         ,
            //         Takimlar = league.Match[i].takimlar
            //         ,
            //         Saat = league.Match[i].saatmac
            //         ,
            //         Iy = league.Scores[i].scorehalfhome + "-" + league.Scores[i].scorehalfaway
            //         ,
            //         Ms = league.Scores[i].scorecurrenthome + "-" + league.Scores[i].scorecurrentaway
            //     });
            //}

            //if (OnCompleteGetResult != null)
            //{
            //    OnCompleteGetResult(this, new EventArgs());
            //}
        }

        /// <summary>
        /// Method to get match programs
        /// </summary>
        /// <param name="dateTime"></param>
        /// <returns></returns>
        public void GetMatchPrograms(DateTime dateTime)
        {
            string matchProgramsUrl = string.Format(MatchProgramsUrl, dateTime.ToString("dd'.'MM'.'yyyy"));
            WebClient wc = GetWebClient();
            wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(GetMatchProgramsCompleted);
            wc.DownloadStringAsync(new Uri(matchProgramsUrl));
        }

        void GetMatchProgramsCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            string result = e.Result;
            result = result.Substring(result.IndexOf("<Draw"));
            result = result.Substring(0, result.IndexOf("<!--"));
            Draw draw = XMLHelper.Deserialize<Draw>(result, Encoding.UTF8);
            //App.MatchPrograms = draw;

        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public void GetLiveMatchResult()
        {
            try
            {
                WebClient wc = GetWebClient();
                wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(GetLiveMatchResultCompleted);
                wc.DownloadStringAsync(new Uri(LiveMatchResultUrl));
            }
            catch (Exception)
            {

            }

        }

        void GetLiveMatchResultCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            string result = e.Result;
            result = result.Substring(result.IndexOf("<Livescores"));
            result = result.Substring(0, result.IndexOf("<!--"));
            Livescores livescores = XMLHelper.Deserialize<Livescores>(result, Encoding.UTF8);
            //App.LiveMatchResult = livescores;

        }

        private WebClient GetWebClient()
        {
            WebClient wc = new WebClient();
            wc.Headers["Accept"] = "*/*";
            wc.Headers["Accept-Charset"] = "ISO-8859-1,utf-8;q=0.7,*;q=0.3";
            wc.Headers["Accept-Encoding"] = "gzip,deflate,sdch";
            wc.Headers["Accept-Language"] = "en-US,en;q=0.8";
            wc.Headers["Cache-Control"] = "no-cache";
            wc.Headers["Host"] = "www.iddaa.com.tr";
            wc.Headers["Referer"] = "http://www.iddaa.com.tr/BITENMACLAR/FUTBOL/index.htm?PROGRAMID=1";
            wc.Headers["User-Agent"] = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.52 Safari/536.5";
            wc.Encoding = Encoding.UTF8;
            return wc;
        }
    }
}
